package com.wnxy.sddfp.trade.utils;

import com.wnxy.sddfp.common.model.exception.Assert;
import com.wnxy.sddfp.common.model.result.enums.impl.BusinessCode;
import com.wnxy.sddfp.common.model.utils.JwtTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class TokenUtils {
    public static String getUserId() {
        // 拿到userId 从token中获取
        // RequestContextHolder  请求的上下文 (在java-web项目中 所有的 请求的数据都可以封装到RequestContextHolder 中(是一种思想))
        // 可以在整个项目中全局 获取 request对象
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String token = request.getHeader("token");

        // token不能为null
        Assert.error(StringUtils.isEmpty(token), BusinessCode.USER_TOKEN_ERROR);

        JwtTemplate jwtTemplate = new JwtTemplate();
        Object value = jwtTemplate.parseToken(token, "userId");
        String userId = value.toString();
        return userId;

    }

    public static Long getTokenUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userId = request.getHeader("userId");
        return Long.parseLong(userId);
    }


    public static String getHeaderUserId() {
        // 拿到userId 从token中获取
        // RequestContextHolder  请求的上下文 (在java web项目中 所有的 请求的数据都可以封装到RequestContextHolder 中(是一种思想))
        // 可以在整个项目中全局 获取 request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        return request.getHeader("userId");

    }
}
